package org.emet.jee.console.services.security;

import java.util.ArrayList;
import java.util.List;

import org.emet.jee.console.entity.security.User;
import org.emet.jee.core.security.springsecurity.SpringSecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
public class SpringSecurityService {
	private static Logger logger = LoggerFactory.getLogger(SpringSecurityService.class);
	@Autowired
	private SecurityEntityManager securityEntityManager;

	public String getCurrentUserName() {
		return SpringSecurityUtils.getCurrentUserName();
	}

	public void keepAlive() {
		// do nothing, just make the session not destroied.
		logger.info("Keep Alive invoked!");
	}

	/**
	 * 获得当前User
	 * 
	 * @return
	 */
	public User getUser() {
		String currentUserName = SpringSecurityUtils.getCurrentUserName();
		User currentUser = securityEntityManager.findUserByLoginName(currentUserName);
		return currentUser;
	}

	public <T extends org.springframework.security.userdetails.User> T getCurrentUser() {
		return SpringSecurityUtils.getCurrentUser();
	}

	/**
	 * 只要拥有一个authority,则返回true
	 */
	public boolean ifAnyGranted(String... authorites) {
		List<String> grantedAuthorities = getCurrentUserAuthorities();

		if (CollectionUtils.isEmpty(grantedAuthorities))
			return false;

		for (String authority : authorites) {
			if (grantedAuthorities.contains(authority))
				return true;
		}
		return false;
	}

	/**
	 * 如果拥有全部authority,则返回true
	 * 
	 */
	public boolean ifAllGranted(String... authorites) {
		List<String> grantedAuthorities = getCurrentUserAuthorities();

		if (CollectionUtils.isEmpty(grantedAuthorities))
			return false;

		for (String authority : authorites) {
			if (!grantedAuthorities.contains(authority))
				return false;
		}
		return true;
	}

	/**
	 * 不包含任何一个authority,则返回true
	 */
	public boolean ifNotGranted(String... authorites) {
		return !ifAnyGranted(authorites);
	}

	/**
	 * 获得当前用户所有的权限
	 */
	public List<String> getCurrentUserAuthorities() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		GrantedAuthority[] grantedAuthorities = auth.getAuthorities();
		List<String> result = new ArrayList<String>();
		for (GrantedAuthority authority : grantedAuthorities) {
			result.add(authority.getAuthority());
		}
		return result;
	}

}
